<template>
  <div class="view">
    <el-row class="handle-box">
      <el-col :span="12">
        <span style="line-height: 60px;padding-left: 15px;">{{$t("document.upload")}}：</span>
        <el-upload
          style="display: inline-block;vertical-align: top;line-height: 60px;"
          class="upload-demo"
          :action="apiurl"
          :headers="Headers"
          :show-file-list="false"
          :before-upload="onBeforeUpload"
          :on-success="handleSuccess"
          :on-error="handleError"
          multiple
          :limit="5"
          :on-exceed="handleExceed"
          :file-list="fileList"
        >
          <el-button style="margin-top: 10px;" class="jianbianbule" size="small" type="primary">{{$t("document.geologyDaily")}}</el-button>
          <span>{{$t("document.upFileSize")}}</span>
        </el-upload>
      </el-col>
      <el-col :span="12" style="text-align: right;">
        <span>{{$t("document.fileName")}}：</span>
        <el-input
          v-model="filters.FileNames"
          @keyup.native.enter="search"
          :placeholder="$t('public.text')"
          clearable
        ></el-input>
        <span>{{$t("document.createDate")}}：</span>
        <el-date-picker
          v-model="filters.UploadDate"
          @change="search"
          align="right"
          type="date"
          :placeholder="$t('public.opDate')"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions"
        >
        </el-date-picker>

        <el-button class="seacthsbtn" type="primary" id="btn" @click="search" icon="el-icon-search">{{$t("public.search")}}</el-button>
      </el-col>
    </el-row>
    <div class="tablebox">
    <!-- 列表 -->
    <template>
      <el-table :data="tables" size="mini" stripe class="tablefisbox">
        <el-table-column type="index" :label="$t('public.number')" width="80">
        </el-table-column>
        <el-table-column prop="fileName" :label="$t('document.fileName')"> </el-table-column>
        <el-table-column prop="fileSize" width="150" :label="$t('document.fileSize')">
        </el-table-column>
        <el-table-column prop="fileTypes" width="150" :label="$t('document.fileTypes')">
        </el-table-column>
        <el-table-column prop="createUser" width="150" :label="$t('document.createUser')">
        </el-table-column>
        <el-table-column
          prop="createDate"
          :label="$t('document.createDate')"
          :formatter="carTimeFilter"
        >
        </el-table-column>
        <el-table-column :label="$t('public.operation')">
          <template slot-scope="scope">
            <el-button
              type="success"
              icon="el-icon-download"
              round
              size="mini"
              @click="handleDown(scope.$index, scope.row)"
              >{{ $t("public.download") }}</el-button
            >

            <el-button
              type="primary"
              icon="el-icon-view"
              round
              size="mini"
              @click="handlePreview(scope.$index, scope.row)"
              >{{ $t("document.preview") }}</el-button
            >

            <el-button
              type="danger"
              icon="el-icon-delete"
              round
              size="mini"
              @click="handleDelete(scope.$index, scope.row)"
              >{{ $t("public.del") }}</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </template>

    <!-- 图片文件预览 -->
    <el-image-viewer
      v-if="showViewer"
      :on-close="()=>{showViewer=false}"
      :url-list="imgList" />

    <!-- PDF文件预览 -->
    <Pdf ref="pdfSearch" :src="pdfUrl" />

    <!-- TXT文件预览 -->
    <TextDialog ref="TextDialog" />

    <!--工具条-->
    <el-col class="pages">
      <el-pagination
        background
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        :current-page="pageSize"
        :total="total"
      >
      </el-pagination>
    </el-col>
    </div>
  </div>
</template>

<script>
import api from "../../../../static/layui/vuepublic";
import Pdf from "../../../components/component/Pdf";
import TextDialog from "../../../components/component/Text";
export default {
  components: {
    "el-image-viewer": () =>
      import("element-ui/packages/image/src/image-viewer"),
    Pdf,
    TextDialog,
  },
  data() {
    return {
      showViewer: false,
      imgList: [], //图片展示
      fileList: [], //上传文件列表
      pdfUrl: "",
      apiurl:
        api.api_address +
        "/doc/uploadgd?usid=" +
        JSON.parse(this.$store.state.userInfo).uid,
      Headers: { Authorization: api.getoken },
      tables: [], //表格数据
      total: 0, //总共条数
      page: 1, //请求页
      limit: 10, //页条数
      pageSize: 1, //当前页
      filters: {
        FileNames: "",
        UploadDate: "",
      },
      pickerOptions: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            },
          },
        ],
      },
    };
  },
  computed: {},
  watch:{
    'filters.FileNames'(val){
      if(val.trim() === ''){
        this.getGeologicalDaily()
      }
    }
  },
  mounted() {
    this.getGeologicalDaily();
  },
  methods: {
    onBeforeUpload(file) {
      const isLt1M = file.size < 20 * 1024 * 1024;
      if (!isLt1M) {
        this.$message.warning("上传文件大小不能超过 20MB!");
      }
      return isLt1M;
    },
    handleExceed(file) {
      this.$message.warning(
        `一次最多上传5个文件，本次选择了 ${file.length} 个文件`
      );
      this.fileList = [];
    },
    //上传成功
    handleSuccess() {
      this.$message({
        message: "上传成功",
        type: "success",
      });
      this.getGeologicalDaily();
    },
    //上传失败
    handleError() {
      this.$message({
        message: "上传失败",
        type: "error",
      });
      this.getGeologicalDaily();
    },

    handleSizeChange(val) {
      this.limit = val;
      this.getGeologicalDaily();
    },
    handleCurrentChange(val) {
      this.page = val;
      this.pageSize = val;
      this.getGeologicalDaily();
    },
    //模糊搜索
    search() {
      this.page = 1;
      this.limit = 10;
      this.pageSize = 1;
      this.getGeologicalDaily();
    },
    //获取
    async getGeologicalDaily() {
      try {
        let params = {
          FileName: this.filters.FileNames,
          UploadDate: this.filters.UploadDate,
          page: this.page,
          limit: this.limit,
        };
        let res = await this.$api.management.getGeologicalDaily(params);
        this.total = res.count;
        this.tables = res.data;
      } catch (e) {
        console.log(e);
      }
    },
    // 删除操作
    handleDelete(index, row) {
      // 二次确认删除
      this.$confirm(
        this.$t("public.confirmcontent"),
        this.$t("public.confirmtitle"),
        {
          type: "warning",
        }
      )
        .then(async () => {
          let params = {
            id: row.gId,
            usid: JSON.parse(this.$store.state.userInfo).uid,
          };
          let res = await this.$api.management.removeGeologicalDaily(params);
          if (res.code == 200) {
            this.$message.success(this.$t("public.confirmtips1"));
            this.getGeologicalDaily(); //刷新数据
          } else {
            this.$message.success("删除失败");
          }
        })
        .catch(() => {
        });
    },
    //下载文件
    handleDown(index, row) {
      let params = {
        url: row.filePath,
        usid: JSON.parse(this.$store.state.userInfo).uid,
      };

      var xmlhr = new XMLHttpRequest();
      xmlhr.open(
        "get",
        api.api_address +
          "/doc/downgd?url=" +
          params.url +
          "&usid=" +
          params.usid,
        true
      );
      //头部请求设置
      xmlhr.setRequestHeader("Authorization", api.getoken);

      xmlhr.responseType = "blob";
      xmlhr.onload = function (oevent) {
        var content = xmlhr.response;
        var elink = document.createElement("a");
        elink.download = row.fileName; //下载后文件名
        elink.style.display = "none";

        var blob = new Blob([content]);
        elink.href = URL.createObjectURL(blob); //创建下载的链接
        elink.click(); //点击下载
        // document.body.removeChild(elink); //下载完成移除元素
      };
      xmlhr.send();
    },
    //文件预览
    async handlePreview(index, row) {
      if (row.fileTypes == "pdf") {
        let that = this;
        var xmlhr = new XMLHttpRequest();
        xmlhr.open(
          "get",
          api.api_address + "/doc/previewgd?id=" + row.gId,
          true
        );
        //头部请求设置
        xmlhr.setRequestHeader("Authorization", api.getoken);

        xmlhr.responseType = "blob";
        xmlhr.onload = function () {
          var content = xmlhr.response;
          const url = window.URL.createObjectURL(content);

          // 将转化后 url 赋值给 vue-pdf 插件
          that.pdfUrl = url;
          that.$refs.pdfSearch.filename = row.fileName;
          that.$refs.pdfSearch.handleOpen();
        };
        xmlhr.send();
      } else if (this.isAssetTypeAnImage(row.fileTypes) == true) {
        let params = {
          id: row.gId,
        };
        let res = await this.$api.management.previewGeologicalDaily(params);

        if (res.code == 200) {
          //图片预览
          if (this.isAssetTypeAnImage(row.fileTypes)) {
            this.showViewer = true;
            let img = ["data:image/bmp;base64," + res.data[0]];
            this.imgList = [];
            this.imgList = img;
          }
        }
      } else if (row.fileTypes == "txt" || row.fileTypes == "las") {
        let that = this;
        let params = {
          id: row.gId,
        };
        let res = await this.$api.management.previewGeologicalDaily(params);
        if (res != null) {
          that.$refs.TextDialog.filename = row.fileName;
          that.$refs.TextDialog.textcont = res;
          that.$refs.TextDialog.handleOpen();
        }
      } else {
        this.$message.warning("该文件暂不支持浏览");
      }
    },
    //日期格式化
    carTimeFilter(row, column, cellValue, index) {
      const daterc = row[column.property];
      if (daterc != null) {
        return this.$moment(daterc).format("YYYY-MM-DD HH:mm:ss");
      }
    },
    //判断是否为图片
    isAssetTypeAnImage(ext) {
      return (
        [
          "png",
          "jpg",
          "jpeg",
          "bmp",
          "gif",
          "webp",
          "psd",
          "svg",
          "tiff",
        ].indexOf(ext.toLowerCase()) !== -1
      );
    },
  },
};
</script>

<style lang='less' scoped>
</style>